import send from '../config/MailConfig'
import bcrypt from 'bcrypt'
import moment from 'moment'
import jsonwebtoken from 'jsonwebtoken'
import config from '@/config/index'
import { checkCode } from '@/common/utils'
import User from '../model/User'
import SignRecord from '@/model/SignRecord'
import uuid from 'uuid/dist/v4'
import { getValue, setValue, getHValue, delValue } from '@/config/RedisConfig';
import jwt from 'jsonwebtoken'
import { getJWTPayload } from "@/common/utils";
class LoginController {
  constructor() { }
  async forget (ctx) {
    const { body } = ctx.request
    //接受数据 验证验证码
    let sid = body.sid, code = body.code
    let ckCode = await checkCode(sid, code);
    if (ckCode) {
      if (!body.username) {
        ctx.body = {
          code: 500,
          msg: '邮箱不能为空',
        }
        return
      }
      //验证用户信息
      let user = await User.findOne({ username: body.username })
      if (user) {
        const key = uuid()
        setValue(key, jwt.sign({ _id: user._id }, config.JWT_SECRET, {
          'expiresIn': '30m'
        }), 10 * 60 * 30)
        try {
          // 通过数据库 email查询user
          let res = await send({
            type: "reset",
            data: {
              key: key,
              username: body.username
            },
            expire: moment().add(30, 'minutes').format('YYYY-MM-DD HH:mm:ss'),
            email: body.username,
            user: user.nickname,
          })
          ctx.body = {
            code: 200,
            data: res,
            msg: '邮件发送成功',
          }
        } catch (e) {
          console.log(e)
        }
      } else {
        ctx.body = {
          code: 500,
          msg: '用户信息不存在',
        }
      }

    } else {
      ctx.body = {
        code: 500,
        msg: '验证码验证失败',
      }
    }

  }

  async login (ctx) {
    //接受数据 验证验证码
    const { body } = ctx.request
    let sid = body.sid, code = body.code
    let ckCode = await checkCode(sid, code);
    if (ckCode) {
      let checkUserPass = false
      //验证用户信息
      let user = await User.findOne({ username: body.username })

      if (await bcrypt.compare(body.password, user.password)) {
        checkUserPass = true
      } else {
        checkUserPass = false;
      }
      if (checkUserPass) {
        const userObj = user.toJSON();
        let arr = ['password', 'username']
        arr.map((item) => {
          delete userObj[item]
        })
        //返回token
        let token = jsonwebtoken.sign({ id: user._id }, config.JWT_SECRET, {
          'expiresIn': '1d'
        })

        //加入isSign 属性
        const signRecord = await SignRecord.findByUid(userObj._id)
        userObj.isSign = false
        if (signRecord !== null) {
          if (moment(signRecord.created).format('YYYY-MM-DD') === moment().format('YYYY-MM-DD')) {
            userObj.isSign = true
          }

          userObj.lastSign = signRecord.created
        }
        ctx.body = {
          code: 200,
          data: userObj,
          token: token
        }
      } else {
        ctx.body = {
          code: 404,
          msg: '用户名或密码错误'
        }
      }

    } else {
      ctx.body = {
        code: 401,
        msg: '图片验证码不正确，请检查'
      }
    }

  }
  async regist (ctx) {
    //接受数据 验证验证码
    const { body } = ctx.request
    let sid = body.sid, code = body.code
    let ckCode = await checkCode(sid, code);
    let check = true
    let msg = {}
    if (ckCode) {
      //验证用户信息
      let user = await User.findOne({ username: body.email })
      if (user) {
        msg.email = '此邮箱已经被注册'
        check = false
      }
      let user1 = await User.findOne({ nickname: body.nickname })
      if (user1) {
        msg.nickname = '此昵称已经被使用'
        check = false
      }

      if (check) {
        body.password = await bcrypt.hash(body.password, 5)
        let newUser = new User({
          username: body.email,
          nickname: body.nickname,
          password: body.password,
          created: moment().format('YYYY-MM-DD HH:mm:ss')
        })
        let res = await newUser.save()
        ctx.body = {
          code: 200,
          data: res,
          msg: '注册成功'
        }
        return;
      }

    } else {
      msg.code = '图片验证码不正确，请检查';
    }

    ctx.body = {
      code: 500,
      msg: msg
    }
  }


  async reset (ctx) {
    const { body } = ctx.request
    const sid = body.sid
    const code = body.code
    let msg = {}
    if (!body.key) {
      ctx.body = {
        code: 500,
        msg: '请求参数异常，请重新获取链接'
      }
      return
    }
    let result = await checkCode(sid, code)
    if (!result) {
      msg.code = '验证码已经失效，请重新获取'
      ctx.body = {
        code: 500,
        msg: msg
      }
      return
    }
    const token = await getValue(body.key)
    if (token) {
      const obj = await getJWTPayload('Bearer ' + token)
      body.password = await bcrypt.hash(body.password, 5)
      await User.updateOne({ _id: obj._id }, {
        password: body.password
      })
      delValue(body.key)
      ctx.body = {
        code: 200,
        msg: '密码修改完毕'
      }
    } else {
      ctx.body = {
        code: 500,
        msg: '链接已经失效'
      }
    }

  }


  async test (ctx) {
    let key = uuid()
    const body = ctx.request.query
    if (!body.username) {

      ctx.body = {
        code: 500,
        msg: '邮箱不能为空',
      }
      return
    }
    //验证用户信息
    let user = await User.findOne({ username: body.username })
    setValue('token', jwt.sign({ _id: user._id }, config.JWT_SECRET, {
      'expiresIn': '30m'
    }), 0)

    await delValue('token')

  }
}




export default new LoginController()
